<template>
  <div class="background">
    <a-card style="margin-bottom: 10px">
      <a-form :form="form" layout="inline" @submit="handleSubmit">
        <a-form-item label="辅料编号">
          <a-input style="width:200px" allow-clear placeholder="请输入辅料编号" v-model="formContent.accCode"></a-input>
        </a-form-item>
        <a-form-item label="辅料大类">
          <a-select style="width: 200px" placeholder="请选择辅料大类" v-model="formContent.accClassifyBig"
            @focus="getDictChildList('CLASSIFY_BIG', 'classifyBigList')" allow-clear>
            <a-select-option :value="item.code" v-for="(item, index) in classifyBigList" :key="index">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="调样单编号">
          <a-input allow-clear style="width:200px" placeholder="请输入调样单编号"
            v-model="formContent.accRetrievalSampleCode"></a-input>
        </a-form-item>
        <a-form-item label="调样单ID">
          <a-input allow-clear style="width:200px" placeholder="请输入调样单ID"
            v-model="formContent.accRetrievalSampleId"></a-input>
        </a-form-item>
        <a-form-item label="状态">
          <a-select style="width: 380px" placeholder="请选择状态" mode="multiple" v-model="formContent.statusList" allow-clear>
            <a-select-option :value="item.value" v-for="(item, index) in statusList" :key="index">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-button type="primary" style="margin-left: 10px" @click="toExamine(10)"
            v-if="auth.includes('acc_r_s_audit_list_dec_audit')">开发审核</a-button>
          <a-button type="primary" style="margin-left: 10px" @click="toExamine(20)"
            v-if="auth.includes('acc_r_s_audit_list_busi_audit')">业务审核</a-button>
          <a-button type="primary" style="margin-left: 10px" @click="toExamine(30)"
            v-if="auth.includes('acc_r_s_audit_list_reject')">退回</a-button>
          <a-button type="primary" style="margin-left: 10px" @click="toExamine(40)"
            v-if="auth.includes('acc_r_s_audit_list_cancel')">作废</a-button>
          <a-button type="primary" style="margin-left: 10px" @click="toUpdate"
            v-if="auth.includes('acc_r_s_audit_list_update')">更新</a-button>
          <a-button type="primary" style="margin-left: 10px" @click="toSync"
            v-if="auth.includes('acc_r_s_audit_list_sync_c17')">同步C17
          </a-button>
        </a-form-item>
      </a-form>

    </a-card>
    <a-card>
      <a-table bordered :loading="loading" :scroll="{ x: 1500,y:500 }" :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows, onChange: onSelectChange }"
        :columns="columns" :data-source="dataSource" @change="handleTableChange">
        <template slot="status" slot-scope="txt, record">
          <span v-for="item, i in statusList" :key="i">
            <span v-if="item.value == record.status">
              {{ item.name }}
            </span></span>
        </template>
        <template slot="category" slot-scope="txt, record">
          <span v-if="record.category == 10">调样</span>
          <span v-else>扩色</span>
        </template>
        <template slot="bigGoodsFlag" slot-scope="txt, record">
          <span v-if="record.bigGoodsFlag == 1">有</span>
          <span v-else>无</span>
        </template>

        <template slot="syncC17Status" slot-scope="txt, record">
          <span v-if="record.syncC17Status == 0">未同步</span>
          <span v-if="record.syncC17Status == 1">正在同步</span>
          <span v-if="record.syncC17Status == 2">已经同步</span>
          <span v-if="record.syncC17Status == 3">同步失败</span>
        </template>
        <template slot="status" slot-scope="txt, record">
          <span v-for="item, i in statusList" :key="i">
            <span v-if="item.value == record.status">
              {{ item.name }}
            </span></span>
        </template>
        <template slot="supplyName" slot-scope="txt, record,i">
          <span @click="toSupply(record, i)" style="color: #409eff;cursor:pointer">
            {{ record.supplyName }}
          </span>
        </template>
        
        <template v-for="col in list" :slot="col" slot-scope="text, record, index">
          <div :key="col">
            <a-date-picker v-if="col == 'predictGoodDate'" v-model="record.predictGoodDate" format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD" />
            <a-date-picker v-if="col == 'practicalGoodDate'" v-model="record.practicalGoodDate" format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD" />
            <a-date-picker v-if="col == 'shipmentsDate'" v-model="record.shipmentsDate" format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD" />
          <a-input style="width: 120px" placeholder="请输入" v-model="record.qty" v-if="col == 'qty'"
              :value="text" />
            <a-input style="width: 120px" placeholder="请输入" v-if="col == 'shipmentsOrderNo'"
              v-model="record.shipmentsOrderNo" :value="text" />
            <!-- <a-input
              style="width: 120px"
              placeholder="请输入"
              v-if="col == 'totalAmount'"
              v-model="record.totalAmount"
              :value="text"
            /> -->
            <a-input style="width: 120px" placeholder="请输入" v-if="col == 'extraCharge'" v-model="record.extraCharge"
              :value="text" />

            <a-textarea style="width: 200px" placeholder="请输入" v-if="col == 'rejectReason'" v-model="record.rejectReason"
              :value="text">
            </a-textarea>

          </div>
        </template>
        <!-- <template
          slot="action"
          slot-scope="txt, record"
        >
          <a-popconfirm
            :title="`确定要删除该项吗?`"
            @confirm="deleteRecord(record)"
          >
            <a class="mr-10">
              删除
            </a>
          </a-popconfirm>
        </template> -->
      </a-table>
      <div v-if="showLoadingMore" :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }">
        <a-spin v-if="loadingMore" />
        <a-button v-else @click="onLoadMore"> loading more </a-button>
      </div>
    </a-card>
    <supply v-if="showSupply" :content="content" @closeSupply="closeSupply"></supply>
  </div>
</template>
  
<script>
import { retrievalsample, getDictChildList, retrievalsampleAudit, retrievalsampleAuditUpdate, retrievalsampleSync } from '@api/material/index'
import { postAction } from '@/api/manage'
import supply from './supply.vue'

const columns = [
  {
    title: '单据编号',
    width: 200,
    dataIndex: 'accRetrievalSampleCode',
    fixed: 'left'
  },
  {
    title: '货季',
    width: 180,
    dataIndex: 'goodsSeasonValue'
  },
  {
    title: '订单类别',
    width: 180,
    dataIndex: 'category',
    scopedSlots: { customRender: 'category' }
  },
  {
    title: '品牌',
    width: 150,
    dataIndex: 'brandValue'
  },
  {
    title: '供应商',
    width: 100,
    dataIndex: 'supplyName',
    scopedSlots: { customRender: 'supplyName' }

  },
  {
    title: '供应商编号',
    width: 150,
    dataIndex: 'supplyCode'
  },
  {
    title: '物料编号',
    width: 120,
    dataIndex: 'accCode'
  },
  {
    title: '物料代码',
    width: 200,
    dataIndex: 'accPriceCode'
  },
  {
    title: '物料名称',
    width: 200,
    dataIndex: 'accName'
  },
  {
    title: '规格',
    width: 100,
    dataIndex: 'materialSpecsName'
  },
  {
    title: '颜色',
    width: 100,
    dataIndex: 'materialColorName'
  },
  {
    title: '数量',
    width: 150,
    dataIndex: 'qty',
    scopedSlots: { customRender: 'qty' }

  },
  {
    title: '单位',
    width: 100,
    dataIndex: 'purchasingUnitValue'
  },
  {
    title: '开发审核日期',
    width: 200,
    dataIndex: 'developerAuditDate'
  },
  {
    title: '业务审核时间',
    width: 200,
    dataIndex: 'businessAuditDate'
  },
  {
    title: '是否有大货',
    width: 150,
    dataIndex: 'bigGoodsFlag',
    scopedSlots: { customRender: 'bigGoodsFlag' }

  },

  {
    title: '要求货期',
    width: 200,
    dataIndex: 'limitDate'
  },
  {
    title: '预计货期',
    width: 200,
    dataIndex: 'predictGoodDate',
    scopedSlots: { customRender: 'predictGoodDate' }
  },
  {
    title: '实际到货日期',
    width: 200,
    dataIndex: 'practicalGoodDate',
    scopedSlots: { customRender: 'practicalGoodDate' }
  },
  {
    title: '发货日期',
    width: 200,
    dataIndex: 'shipmentsDate',
    scopedSlots: { customRender: 'shipmentsDate' }
  },
  {
    title: '发货单号',
    width: 200,
    dataIndex: 'shipmentsOrderNo',
    scopedSlots: { customRender: 'shipmentsOrderNo' }
  },
  {
    title: '价格',
    width: 100,
    dataIndex: 'price',
  },
  {
    title: '税率',
    width: 100,
    dataIndex: 'taxRate'
  },
  {
    title: '金额',
    width: 150,
    dataIndex: 'totalAmount',
    // scopedSlots: { customRender: 'totalAmount' }
  },
  {
    title: '附加费用',
    width: 150,
    dataIndex: 'extraCharge',
    scopedSlots: { customRender: 'extraCharge' }
  },
  {
    title: '同步c17状态',
    width: 220,
    dataIndex: 'syncC17Status',
    scopedSlots: { customRender: 'syncC17Status' }
  },
  {
    title: '同步c17的单号',
    width: 300,
    dataIndex: 'syncC17OrderNo',
    scopedSlots: { customRender: 'syncC17OrderNo' }
  },
  {
    title: '状态',
    width: 140,
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '备注',
    width: 200,
    dataIndex: 'remark'
  },

  {
    title: '退回原因',
    width: 200,
    dataIndex: 'rejectReason',
    scopedSlots: { customRender: 'rejectReason' }
  },
  // {
  //   title: '操作',
  //   width: 80,
  //   fixed: 'right',
  //   scopedSlots: { customRender: 'action' }
  // }
]
export default {
  components: {
    supply
  },
  data() {
    return {
      urlKey: 'basemgt-material/',
      columns,
      showLoadingMore: false,
      loadingMore: false,
      statusList: [
        { value: 20, name: '待开发审核' },
        { value: 30, name: '待业务审核' },
        { value: 40, name: '业务已审核' }
      ],
      form: this.$form.createForm(this),
      loading: false,
      dataSource: [],
      auth: [],
      selectedRowKeys: [],
      selectedRows: [],
      current: 1,
      pageSize: 100,
      classifyBigList: [],
      content: {},
      indexNum: '',
      showSupply: false,
      formContent: {
        accRetrievalSampleId: '',
        accRetrievalSampleCode: '',
        accClassifyBig: undefined,
        accCode: '',
        statusList: [20, 30, 40]
      },
      list: ['predictGoodDate', 'practicalGoodDate', 'shipmentsDate', 'shipmentsOrderNo', 'price', 'qty', 'extraCharge', 'rejectReason']
    }
  },
  computed: {
    jobNumber() {
      return this.$store.getters.userInfo.workNo || ''
    }
  },
  mounted() {
    this.getList()
    this.getAuth()
  },

  methods: {
    onLoadMore() {
      this.loadingMore = true
      this.current += 1
      this.getList()
    },
    toSupply(record, i) {
      this.showSupply = true
      this.content = record
      this.indexNum = i
    },
    closeSupply(supply) {
      this.showSupply = false
      if (supply) {
        this.dataSource[this.indexNum].supplyCode = supply.supplyCode
        this.dataSource[this.indexNum].supplyName = supply.supplyName
        this.dataSource[this.indexNum].price = supply.purchaseTaxTratePrice
        this.dataSource[this.indexNum].taxRate = supply.taxRate

      }
    },
    async toExamine(type) {
      const newArr = []
      this.selectedRows.map(item => {
        const obj = {
          accRetrievalSampleDetailId: item.accRetrievalSampleDetailId
        }
        if (type == 30) {
          obj.rejectReason = item.rejectReason
        }
        newArr.push(obj)
      })
      const params = {
        detail: newArr,
        jobNumber: this.jobNumber,
        operation: type
      }
      try {
        const res = await retrievalsampleAudit(params)
        if (res.code == 200) {
          this.$message.success('操作成功！')
          this.current = 1
          this.getList()
        } else {
          if (res.msg) {
            let that = this
            that.$confirm({
              title: res.msg,
              cancelText: '取消',
              onOk: res => {
                console.log(res)
                return new Promise((resolve, reject) => {
                  reject().catch(err => {
                    resolve()
                    console.log(err)
                  })
                }).catch(() => console.log('Oops errors!'))
              },
              onCancel() { }
            })
          }
        }
      } catch (error) {
        this.$message.error('操作失败！')
      }
    },
    async toSync() {
      const newArr = []
      this.selectedRows.map(item => {
        newArr.push(item.accRetrievalSampleDetailId)
      })
      const params = {
        accRetrievalSampleDetailIdList: newArr,
        jobNumber: this.jobNumber
      }
      try {
        const res = await retrievalsampleSync(params)
        if (res.code == 200) {
          this.$message.success('操作成功！')
          this.current = 1
          this.getList()
        } else {
          if (res.msg) {
            let that = this
            that.$confirm({
              title: res.msg,
              cancelText: '取消',
              onOk: res => {
                console.log(res)
                return new Promise((resolve, reject) => {
                  reject().catch(err => {
                    resolve()
                    console.log(err)
                  })
                }).catch(() => console.log('Oops errors!'))
              },
              onCancel() { }
            })
          }
        }
      } catch (error) {
        this.$message.error('操作失败！')
      }
    },
    async toUpdate() {
      const newArr = []
      this.selectedRows.map(item => {
        const obj = {
          accRetrievalSampleDetailId: item.accRetrievalSampleDetailId,
          extraCharge: item.extraCharge,
          practicalGoodDate: item.practicalGoodDate,
          predictGoodDate: item.predictGoodDate,
          rejectReason: item.rejectReason,
          shipmentsDate: item.shipmentsDate,
          shipmentsOrderNo: item.shipmentsOrderNo,
          // totalAmount: item.totalAmount
        }
        if (item.status != 40) {
          obj.price = item.price
          obj.qty = item.qty
          obj.taxRate = item.taxRate
          obj.supplyCode = item.supplyCode
        }
        newArr.push(obj)
      })
      const params = {
        detail: newArr,
        jobNumber: this.jobNumber
      }
      try {
        const res = await retrievalsampleAuditUpdate(params)
        if (res.code == 200) {
          this.$message.success('操作成功！')
          this.current = 1
          this.getList()
        } else {
          if (res.msg) {
            let that = this
            that.$confirm({
              title: res.msg,
              cancelText: '取消',
              onOk: res => {
                console.log(res)
                return new Promise((resolve, reject) => {
                  reject().catch(err => {
                    resolve()
                    console.log(err)
                  })
                }).catch(() => console.log('Oops errors!'))
              },
              onCancel() { }
            })
          }
        }
      } catch (error) {
        this.$message.error('操作失败！')
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      console.log(this.selectedRows)
    },
    handleTableChange(pagination) {
      this.pagination = pagination
      this.getList()
    },
    handleSubmit(e) {
      e.preventDefault()
      this.getList(1)
    },
    async getDictChildList(name, list) {
      const params = {
        name: name
      }
      try {
        const res = await getDictChildList(params)
        if (res.code == 200) {
          this[list] = res.data
        } else {
          if (res.msg) {
            this.$message.error(res.msg)
          } else {
            this.$message.error('获取数据字典失败！')
          }
        }
      } catch (error) {
        this.$message.error('获取数据字典失败！')
      }
    },
    getAuth() {
      const params = {
        pageCode: 'acc_r_s_audit_list',
        jobNumber: this.jobNumber
      }
      postAction(`${this.urlKey}account/auth`, params).then(res => {
        if (res.code == 200) {
          this.auth = res.data
        }
      })
    },
    async getList(key) {
      this.loading = true
      const params = this.formContent
      params.current = this.current
      params.size = this.pageSize
      if (key) {
        params.current = 1
      }
      try {
        const res = await retrievalsample(params)
        if (res.code == 200) {
          if (params.current == 1) {
            this.dataSource = res.data.records
          } else {
            this.dataSource = this.dataSource.concat(res.data.records)
          }
          if (this.dataSource.length < res.data.total) {
            this.showLoadingMore = true
          } else {
            this.showLoadingMore = false
          }
        } else {
          this.$message.warning(res.msg)
        }
      } catch (error) {
        this.$message.warning('获取列表失败！')
      } finally {
        this.loading = false
        this.loadingMore = false
        this.loading = false
      }
    },
  }
}
</script>
<style lang="less" scoped>
.background {
  background: transparent;
}

.mr-10 {
  margin-left: 10px;
}
</style>